<template>
	<div class="app-container">
		<!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch && !hideUI"
			label-width="68px">
			<el-form-item label="姓名" prop="name">
				<el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="电话" prop="phone">
				<el-input v-model="queryParams.phone" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="学生" prop="idCardNumber">
				<el-input v-model="queryParams.idCardNumber" placeholder="请输入学生号码" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="校区" prop="cellId">
				<el-select v-model="queryParams.cellId" placeholder="请选择校区" clearable @change="handleQueryCellChange">
					<el-option v-for="item in cellOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>

			<el-form-item label="入住状态" prop="isFlag">
				<el-select v-model="queryParams.isFlag" placeholder="请选择入住状态" clearable>
					<el-option v-for="dict in dict.type.nnnn" :key="dict.value" :label="dict.label"
						:value="parseInt(dict.value)" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form> -->

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['tenantuser:tenant:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-switch-button" size="mini" @click="handleRoomCheckOut"
					v-hasPermi="['tenantuser:tenant:home']">房间退租</el-button>
			</el-col>
			<!--   <el-col :span="1.5" v-if="!hideUI">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tenantuser:tenant:edit']"
        >修改</el-button>
      </el-col> -->
			<!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tenantuser:tenant:remove']"
        >删除</el-button>
      </el-col> -->
			<el-col :span="1.5" v-if="!hideUI">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['tenantuser:tenant:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table 
			v-loading="loading" 
			:data="tenantList" 
			@selection-change="handleSelectionChange"
			:max-height="tableMaxHeight"
			style="width: 100%"
			stripe
			border
			highlight-current-row
		>
			<!-- <el-table-column type="selection" width="55" align="center" v-if="!hideUI" /> -->
			<!-- <el-table-column label="编号" align="center" prop="id" /> -->
			<el-table-column label="姓名" align="center" prop="name" />
			<!-- <el-table-column label="电话" align="center" prop="phone" /> -->
			<el-table-column label="卡号" align="center" prop="cardNo" />
			<el-table-column label="类别" align="center" prop="type">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.relation" :value="scope.row.type" />
				</template>
			</el-table-column>


			<el-table-column label="学生工号" align="center" prop="idCardNumber" />
			<!--     <el-table-column label="位置信息" align="center" width="280" v-if="!hideUI">
        <template slot-scope="scope">
          <span>{{ scope.row.cellName || '' }}-{{ scope.row.unitName || '' }}-{{ scope.row.floorName || '' }}-{{ scope.row.roomName || '' }}</span>
        </template>
      </el-table-column> -->
			<el-table-column label="状态" align="center" prop="isFlag">
				<template slot-scope="scope">
          <dict-tag :options="dict.type.delete_flg_type" :value="scope.row.isFlag"/>
				</template>
			</el-table-column>

			<el-table-column label="入住时间" align="center" prop="startTime" />
			<el-table-column label="离开时间" align="center" prop="endTime" />
			<!-- <el-table-column label="入住房间数" align="center" prop="roomCount" /> -->

			<!-- <el-table-column label="创建时间" align="center" prop="createTime" /> -->
			<!-- <el-table-column label="备注" align="center" prop="remark" v-if="!hideUI" /> -->
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-key" @click="handleKeyAuth(scope.row)"
						v-hasPermi="['lock:tenantkey:edit']">新增钥匙</el-button>
					<!-- <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
						v-hasPermi="['tenantuser:tenant:query']">详情</el-button> -->
            <el-button size="mini" type="text" icon="el-icon-switch-button" @click="handleCheckOut(scope.row)"
            	v-hasPermi="['tenantuser:tenant:tuifang']">退房</el-button>
		<!-- 			<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['tenantuser:tenant:edit']">修改</el-button> -->
					<!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tenantuser:tenant:remove']"
          >删除</el-button> -->
					<!-- 合同按钮去掉 -->
					<!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleContract(scope.row)"
            v-hasPermi="['lock:tenantkey:edit']"
          >合同</el-button> -->
					<!-- <el-button size="mini" type="text" icon="el-icon-s-tools" @click="handleStatus(scope.row)"
						v-hasPermi="['tenantuser:tenant:edit']">状态管理</el-button> -->
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改人员信息对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<!-- 基本信息 -->
				<el-row>
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="form.name" placeholder="请输入姓名" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电话" prop="phone">
							<el-input v-model="form.phone" placeholder="请输入电话" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="卡号" prop="cardNo">
							<el-input v-model="form.cardNo" placeholder="请输入卡号" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="性别" prop="gender">
							<el-select v-model="form.gender" placeholder="请选择性别">
								<el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
									:value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

				</el-row>
				<!-- 学生信息 -->
				<el-row>
					<el-col :span="24">
						<el-form-item label="学生号码" prop="idCardNumber">
							<el-input v-model="form.idCardNumber" placeholder="请输入学生号码" />
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 位置信息 -->
				<template v-if="!hideUI">
					<el-row>
						<el-col :span="12">
							<el-form-item label="类别" prop="type">
								<el-select v-model="form.type" placeholder="请选择类别">
									<el-option v-for="dict in dict.type.relation" :key="dict.value" :label="dict.label"
										:value="dict.value" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</template>

				<!-- 入住时间信息 -->
				<el-row>
					<el-col :span="12">
						<el-form-item label="入住时间" prop="startTime">
								<el-date-picker
									class="dataPick"
									v-model="form.startTime"
									type="datetime"
									placeholder="选择入住时间"
									value-format="yyyy-MM-dd HH:mm:ss"
									:popper-class="'currentDatePickerClass'"
									:picker-options="{
										disabledDate: time => {
											return time.getTime() < Date.now() - 8.64e7;
										}
									}"
									@change="onStartTimeChange"
								/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="离开时间" prop="endTime">
								<el-date-picker
									class="dataPick"
									v-model="form.endTime"
									type="datetime"
									placeholder="选择离开时间"
									value-format="yyyy-MM-dd HH:mm:ss"
									:popper-class="'currentDatePickerClass'"
									:picker-options="{
										disabledDate: time => {
											if (form.startTime) {
												return time.getTime() <= new Date(form.startTime).getTime();
											}
											return time.getTime() < Date.now();
										}
									}"
								/>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 其他信息 -->

				<!-- 备注信息 -->
				<el-row>
					<el-col :span="24">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 详情对话框 -->
		<el-dialog :visible.sync="detailOpen" title="人员详情" width="70%">
			<el-tabs v-model="activeTab" @tab-click="handleTabChange">
				<el-tab-pane label="基本信息" name="base">
					<el-descriptions :column="2" border>
						<el-descriptions-item label="姓名">{{ detailForm.name || '-' }}</el-descriptions-item>
						<el-descriptions-item label="电话">{{ detailForm.phone || '-' }}</el-descriptions-item>
						<el-descriptions-item label="学工号">{{ detailForm.idCardNumber || '-' }}</el-descriptions-item>
						<el-descriptions-item label="性别">
							<dict-tag :options="dict.type.sys_user_sex" :value="detailForm.gender" />
						</el-descriptions-item>
						<el-descriptions-item label="入住状态">
							<dict-tag :options="dict.type.ruzhu_status_type" :value="detailForm.isFlag" />
						</el-descriptions-item>
						<el-descriptions-item label="入住时间">{{ detailForm.startTime || '-' }}</el-descriptions-item>
						<el-descriptions-item label="离开时间">{{ detailForm.endTime || '-' }}</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{ detailForm.createTime || '-' }}</el-descriptions-item>
						<el-descriptions-item label="备注">{{ detailForm.remark || '-' }}</el-descriptions-item>
					</el-descriptions>
				</el-tab-pane>
				<!-- 合同信息tab去掉 -->
				<!-- <el-tab-pane label="合同信息" name="contract"> ... </el-tab-pane> -->
			</el-tabs>
			<span slot="footer" class="dialog-footer">
				<el-button @click="detailOpen = false">关闭</el-button>
			</span>
		</el-dialog>

		<!-- 授权钥匙组件 -->
		<key-auth ref="keyAuth" @refresh="getList"></key-auth>

		<!-- 密码修改对话框 -->
		<el-dialog :title="'修改密码'" :visible.sync="passwordOpen" width="400px">
			<el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
				<el-form-item label="密码" prop="password">
					<el-input v-model="passwordForm.password" type="password" placeholder="请输入新的6位数字密码" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitPasswordForm">确定</el-button>
				<el-button @click="cancelPassword">取消</el-button>
			</div>
		</el-dialog>

		<!-- 添加状态管理对话框 -->
		<el-dialog :title="'人员状态管理'" :visible.sync="statusDialog" width="400px">
			<el-form ref="statusForm" :model="statusForm" label-width="100px">
				<el-form-item label="姓名">
					<span>{{ currentTenant.name }}</span>
				</el-form-item>
				<el-form-item label="入住状态" prop="isFlag">
					<el-select v-model="statusForm.isFlag" placeholder="请选择入住状态">
						<el-option v-for="dict in dict.type.ruzhu_status_type" :key="dict.value" :label="dict.label"
							:value="parseInt(dict.value)"></el-option>
					</el-select>
					<!-- 添加退租警告提示 -->
					<div v-if="statusForm.isFlag === 2" class="warning-tip">
						<i class="el-icon-warning"></i> 警告：如果退租，人员下的钥匙请手动删除
					</div>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitStatusForm">确 定</el-button>
				<el-button @click="statusDialog = false">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 选择未入住用户对话框 -->
		<el-dialog
			title="选择未入住用户"
			:visible.sync="addUserDialogVisible"
			width="1700px"
			class="batch-add-dialog"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			top="5vh"
		>
			<div class="dialog-content">
				<el-row :gutter="24">
					<!-- 左侧：用户选择区域 -->
					<el-col :span="14">
						<div class="user-selection-section">
							<div class="section-header">
								<i class="el-icon-user"></i>
								<span class="section-title">选择用户</span>
								<span class="required-badge">必填</span>
							</div>
							<div class="selection-tip">
								<div>
								<i class="el-icon-info"></i>
									<span>请从左侧选择要添加的用户</span>
								</div>
								<div v-if="notRuzhuUserTotal > 0" class="user-count-tip">
									<span>共 {{ notRuzhuUserTotal }} 个未入住用户，当前显示 {{ notRuzhuUserList.length }} 个</span>
									<div v-if="allSelectedUsers.length > 0" style="margin-top: 4px;">
										<span style="font-size: 12px; color: #67c23a;">✓ 已选择 {{ allSelectedUsers.length }} 个用户</span>
									</div>
								</div>
							</div>
							<div class="transfer-container">
								<!-- 搜索框 -->
								<div class="search-container">
									<el-input
										v-model="searchKeyword"
										placeholder="输入姓名或学工号搜索"
										prefix-icon="el-icon-search"
										clearable
										@input="handleSearchInput"
										@clear="handleSearchClear"
										style="margin-bottom: 15px;"
									/>
								</div>

								<el-transfer
									v-model="selectedUserIds"
									:data="getTransferData()"
									:filterable="false"
									:titles="['未入住用户', '已选择用户']"
									:props="{key: 'key', label: 'label'}"
									class="custom-transfer"
									:left-default-checked="[]"
									:right-default-checked="[]"
									:loading="notRuzhuUserLoading"
									@change="handleTransferChange"
								/>
								<!-- 分页组件 -->
								<div class="transfer-pagination">
									<el-pagination
										@size-change="handleNotRuzhuUserSizeChange"
										@current-change="handleNotRuzhuUserCurrentChange"
										:current-page="notRuzhuUserQuery.pageNum"
										:page-sizes="[10, 20, 50, 100]"
										:page-size="notRuzhuUserQuery.pageSize"
										layout="total, sizes, prev, pager, next, jumper"
										:total="notRuzhuUserTotal"
										small
										background
									>
									</el-pagination>
								</div>
							</div>
						</div>
					</el-col>

					<!-- 右侧：入住时间设置 -->
					<el-col :span="10">
						<div class="time-setting-section" :class="{ 'time-section-active': selectedUserIds.length > 0 }">
							<div class="section-header">
								<i class="el-icon-time"></i>
								<span class="section-title">入住时间设置</span>
								<span class="required-badge">必填</span>
							</div>

							<div v-if="selectedUserIds.length > 0" class="time-content">
								<div class="selection-tip">
									<i class="el-icon-info"></i>
									<span>请设置用户的入住开始时间和结束时间</span>
								</div>
								<el-form ref="batchForm" :model="batchForm" :rules="batchRules" label-width="80px" class="time-form">
									<el-form-item label="入住时间" prop="startTime">
											<el-date-picker
												class="dataPick"
												v-model="batchForm.startTime"
												type="datetime"
												placeholder="选择入住时间"
												value-format="yyyy-MM-dd HH:mm:ss"
												style="width: 100%"
												prefix-icon="el-icon-date"
												:popper-class="'currentDatePickerClass'"
												@change="onBatchStartTimeChange"
											/>
									</el-form-item>
									<el-form-item label="离开时间" prop="endTime">
											<el-date-picker
												class="dataPick"
												v-model="batchForm.endTime"
												type="datetime"
												placeholder="选择离开时间"
												value-format="yyyy-MM-dd HH:mm:ss"
												style="width: 100%"
												prefix-icon="el-icon-date"
												:popper-class="'currentDatePickerClass'"
												:picker-options="{
													disabledDate: time => {
														if (batchForm.startTime) {
															return time.getTime() <= new Date(batchForm.startTime).getTime();
														}
														return false;
													}
												}"
											/>
									</el-form-item>
								</el-form>
							</div>

							<div v-else class="time-placeholder">
								<div class="placeholder-icon">
									<i class="el-icon-time"></i>
								</div>
								<div class="placeholder-text">
									<p>请先选择用户</p>
									<span>选择用户后将显示时间设置选项</span>
								</div>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>

			<span slot="footer" class="dialog-footer">
				<el-button @click="addUserDialogVisible = false" size="medium">取消</el-button>
				<el-button
					type="primary"
					@click="handleAddUserConfirm"
					:disabled="!canConfirm"
					size="medium"
					icon="el-icon-check"
				>
					确定添加
				</el-button>
			</span>
		</el-dialog>

		<!--    <el-empty v-if="tenantList.length === 0 && !loading" description="暂无人员信息"></el-empty> -->
	</div>
</template>

<script>
	import {
		listTenantRuzhu,
		getTenant,
		getTenantRuzhuInfo,
		delTenant,
		addTenant,
		updateTenant,
		updateTenantStatus,
		listTenantNotRuzhu,
		addHomeUser,
		apartmentRoomSingleCheckOut,
		roomCheckOut
	} from "@/api/lock/tenantUser";
	import {
		listTenantkey,
		delTenantkey,
		updateTenantkey
	} from "@/api/lock/tenantkey";
	import KeyAuth from "@/views/lock/room/keyAuth/index";

	// 定义一个独立的 formatDateTime 函数
	function formatDateTime(dateTimeStr) {
		// 创建一个 Date 对象
		const date = new Date(dateTimeStr);

		// 提取年、月、日、时、分、秒
		// 注意：月份是从 0 开始的，所以需要加 1
		const year = date.getFullYear();
		const month = ('0' + (date.getMonth() + 1)).slice(-2);
		const day = ('0' + date.getDate()).slice(-2);
		const hours = ('0' + date.getHours()).slice(-2);
		const minutes = ('0' + date.getMinutes()).slice(-2);
		const seconds = ('0' + date.getSeconds()).slice(-2);

		// 重新格式化日期时间字符串
		const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

		return formattedDateTime;
	}

	export default {
		name: "Tenant",
		dicts: ['sys_user_sex', 'delete_flg_type', 'freeze_status_type', 'contract_type', 'contract_status', 'key_type',
			'is_effectiveness', 'relation'
		],
		components: {
			KeyAuth
		},
		props: {
			// 房间ID
			homeId: {
				type: [String, Number],
				default: null
			},
			// 控制搜索和工具栏的显示
			hideUI: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 人员信息表格数据
				tenantList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					name: null,
					phone: null,
					idCardNumber: null,
					type: null,
					isFlag: null,
					homeId: null
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					startTime: [{
						required: true,
						message: '请选择入住时间',
						trigger: 'blur'
					}],
					endTime: [{
						required: true,
						message: '请选择离开时间',
						trigger: 'blur'
					}, {
						validator: (rule, value, callback) => {
							if (value && this.form.startTime) {
								const startTime = new Date(this.form.startTime).getTime();
								const endTime = new Date(value).getTime();
								if (endTime <= startTime) {
									callback(new Error('离开时间必须大于入住时间'));
								} else {
									callback();
								}
							} else {
								callback();
							}
						},
						trigger: 'change'
					}]
				},
				// 办理状态弹窗
				statusDialog: false,
				// 当前选中的人员
				currentTenant: {},
				// 状态表单数据
				statusForm: {},
				// 授权钥匙相关数据
				isShow: false,
				radioType: '1',
				showCustom: false,
				showka: true,
				radio: null,
				// 钥匙表单参数
				keyForm: {
					cardNo: "",
				},
				// 添加密码、卡片校验
				rulesNEW: {
					startTime: [{
						required: true,
						message: '请选择开始时间',
						trigger: 'blur'
					}],
					endTime: [{
						required: true,
						message: '请选择结束时间',
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}],
					cardNo: [{
						required: true,
						message: '请输入卡号',
						trigger: 'blur'
					}]
				},
				// 详情对话框相关数据
				detailOpen: false,
				activeTab: 'base',
				detailForm: {},
				// 密码修改相关数据
				passwordOpen: false,
				passwordForm: {},
				passwordRules: {
					password: [{
							required: true,
							message: "密码不能为空",
							trigger: "blur"
						},
						{
							min: 6,
							max: 6,
							message: "密码必须是6位",
							trigger: "blur"
						},
						{
							pattern: /^\d{6}$/,
							message: "密码必须是6位数字",
							trigger: "blur"
						}
					]
				},
				// 新增未入住用户相关数据
				notRuzhuUserList: [],
				selectedUserIds: [],
				allSelectedUsers: [], // 存储所有已选择的用户完整信息
				addUserDialogVisible: false,
				batchForm: {
					startTime: null,
					endTime: null
				},
				// 未入住用户分页参数
				notRuzhuUserQuery: {
					pageNum: 1,
					pageSize: 20,
					homeId: null,
					name: '', // 姓名搜索字段
					idCardNumber: '' // 学工号搜索字段
				},
				notRuzhuUserTotal: 0,
				notRuzhuUserLoading: false,
				searchTimer: null, // 搜索防抖定时器
				searchKeyword: '', // 搜索关键词
				// 批量添加用户表单验证规则
				batchRules: {
					startTime: [{
						required: true,
						message: '请选择入住时间',
						trigger: 'change'
					}],
					endTime: [{
						required: true,
						message: '请选择离开时间',
						trigger: 'change'
					}, {
						validator: (rule, value, callback) => {
							if (value && this.batchForm.startTime) {
								const startTime = new Date(this.batchForm.startTime).getTime();
								const endTime = new Date(value).getTime();
								if (endTime <= startTime) {
									callback(new Error('离开时间必须大于入住时间'));
								} else {
									callback();
								}
							} else {
								callback();
							}
						},
						trigger: 'change'
					}]
				},
				// 表格最大高度
				tableMaxHeight: 500,
			};
		},
		computed: {
			endPickerOptions() {
				return {
					disabledDate: time => {
						const startTime = new Date(this.keyForm.startTime).setHours(0, 0, 0, 0); // 设置开始时间的时、分、秒、毫秒为0
						const currentDate = new Date().setHours(0, 0, 0, 0); // 当前日期的时、分、秒、毫秒为0

						// 禁止选择开始时间之前的日期或当天
						return time.getTime() < startTime - 86400000 || time.getTime() < currentDate;
					}
				};
			},
			defaultTime() {
				return '00:00:00'; // 指定的默认时分秒
			},
			// 是否为嵌入模式
			isEmbedded() {
				return this.hideUI === true;
			},
			// 是否可以确认添加用户
			canConfirm() {
				return this.selectedUserIds.length > 0 && this.batchForm.startTime && this.batchForm.endTime;
			}
		},
		watch: {
			// 监听homeId的变化，重新加载数据
			homeId: {
				handler(newVal) {
					if (newVal) {

						this.queryParams.homeId = newVal;
						this.queryParams.isFlag = 1;
						this.getList();
					}
				},
				immediate: true
			},
			// 监听数据变化，重新计算表格高度
			tenantList: {
				handler() {
					this.$nextTick(() => {
						this.calculateTableHeight();
					});
				},
				deep: true
			}
		},
		created() {
			// 先加载校区数据

		},
		mounted() {
			// 如果是嵌入模式，添加样式类
			if (this.isEmbedded) {
				this.$nextTick(() => {
					const container = this.$el.querySelector('.app-container');
					if (container) {
						container.classList.add('embedded-mode');
					}
				});
			}
			
			// 计算表格最大高度
			this.calculateTableHeight();
			
			// 监听窗口大小变化
			window.addEventListener('resize', this.calculateTableHeight);
		},
		methods: {
			/** 查询人员信息列表 */
			getList() {
				this.loading = true;
				// 确保每次查询都用上最新的homeId
				if (this.homeId) {
					this.queryParams.homeId = Number(this.homeId);
				}
				listTenantRuzhu(this.queryParams).then(response => {
					this.tenantList = response.rows;
					// 不再需要手动处理位置信息，因为后台会直接返回
					this.total = response.total;
					this.loading = false;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					name: null,
					phone: null,
					type: null,
					idCardPositive: null,
					idCardReverse: null,
					idCardNumber: null,
					startTime: null,
					endTime: null,
					homeId: null,
					unitId: null,
					floorId: null,
					cellId: null,
					isFlag: null,
					gender: null,
					createBy: null,
					updateBy: null,
					updateTime: null,
					createTime: null,
					remark: null,
					userId: null,
					flgDelete: null
				};
				this.resetForm("form");
				// 清空选项数据
				this.unitOptions = [];
				this.floorOptions = [];
				this.homeOptions = [];
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				// 确保入住状态参数正确传递
				if (this.queryParams.isFlag === '') {
					this.queryParams.isFlag = null;
				}
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				// 重置所有查询参数
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
					name: null,
					phone: null,
					idCardNumber: null,
					type: null,
					isFlag: null,
					homeId: null
				};
				this.handleQuery();
				// 清空选项数据
				this.unitOptions = [];
				this.floorOptions = [];
				this.homeOptions = [];
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.handleAddUserDialog();
			},
			/** 修改按钮操作 */
			async handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids;
				try {
					// 如果有homeId，使用新的API查询入住用户信息
					if (this.homeId) {
						const response = await getTenantRuzhuInfo({
							id: id,
							homeId: this.homeId
						});
						const data = response.data;

						// 转换办理状态为数字类型
						if (data.isFlag !== null && data.isFlag !== undefined) {
							data.isFlag = parseInt(data.isFlag);
						}

						// 所有数据加载完成后，再设置表单数据
						this.form = data;
						this.form.homeId = this.homeId;
					} else {
						// 如果没有homeId，使用原来的API
						const response = await getTenant(id);
						const data = response.data;

						// 转换办理状态为数字类型
						if (data.isFlag !== null && data.isFlag !== undefined) {
							data.isFlag = parseInt(data.isFlag);
						}

						// 所有数据加载完成后，再设置表单数据
						this.form = data;
					}

					this.open = true;
					this.title = "修改人员信息";
				} catch (error) {
					console.error('加载数据失败:', error);
				}
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.id != null) {
							updateTenant(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addTenant(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除人员信息编号为"' + ids + '"的数据项？').then(function() {
					return delTenant(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('tenantuser/tenant/export', {
					...this.queryParams
				}, `tenant_${new Date().getTime()}.xlsx`)
			},


			/** 表单校区选择改变时触发 */
			handleCellChange(value) {
				if (!value) {
					this.form.unitId = undefined;
					this.form.floorId = undefined;
					this.form.homeId = undefined;
					this.unitOptions = [];
					this.floorOptions = [];
					this.homeOptions = [];
					return;
				}
				this.getUnitList(value);
			},
			/** 表单楼栋选择改变时触发 */
			handleUnitChange(value) {
				if (!value) {
					this.form.floorId = undefined;
					this.form.homeId = undefined;
					this.floorOptions = [];
					this.homeOptions = [];
					return;
				}
				this.getFloorList(value);
			},
			/** 表单楼层选择改变时触发 */
			handleFloorChange(value) {
				if (!value) {
					this.form.homeId = undefined;
					this.homeOptions = [];
					return;
				}
				this.getRoomList(value);
			},
			/** 搜索条件校区选择改变时触发 */
			handleQueryCellChange(value) {
				if (!value) {
					this.queryParams.unitId = undefined;
					this.queryParams.floorId = undefined;
					this.queryParams.homeId = undefined;
					this.unitOptions = [];
					this.floorOptions = [];
					this.homeOptions = [];
					return;
				}
				this.getUnitList(value);
			},
			/** 搜索条件楼栋选择改变时触发 */
			handleQueryUnitChange(value) {
				if (!value) {
					this.queryParams.floorId = undefined;
					this.queryParams.homeId = undefined;
					this.floorOptions = [];
					this.homeOptions = [];
					return;
				}
				this.getFloorList(value);
			},
			/** 搜索条件楼层选择改变时触发 */
			handleQueryFloorChange(value) {
				if (!value) {
					this.queryParams.homeId = undefined;
					this.homeOptions = [];
					return;
				}
				this.getRoomList(value);
			},
			/** 将楼层数字转换为名称 */
			getFloorName(floor) {
				const floorNum = parseInt(floor);
				if (isNaN(floorNum)) return floor;

				if (floorNum < 0) {
					return `地下${Math.abs(floorNum)}层`;
				} else {
					return `${floorNum}层`;
				}
			},
			/** 办理状态按钮操作 */
			handleStatus(row) {
				this.currentTenant = JSON.parse(JSON.stringify(row));
				this.statusForm = {
					id: row.id,
					isFlag: row.isFlag || 0
				};
				this.statusDialog = true;
			},
			/** 提交状态表单 */
			submitStatusForm() {
				// 如果是退租状态，显示确认对话框
				if (this.statusForm.isFlag === 0 || this.statusForm.isFlag === 2) {
					this.$confirm('确认要将该人员状态修改为退租吗？此操作将删除该人员下的所有密码和授权', '退租确认', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.updateTenantStatus();
					}).catch(() => {
						// 用户取消操作，不做任何处理
					});
				} else {
					// 非退租状态，直接更新
					this.updateTenantStatus();
				}
			},
			/** 更新人员状态 */
			updateTenantStatus() {
				const tenant = {
					id: this.statusForm.id,
					isFlag: this.statusForm.isFlag
				};

				// 使用包含钥匙删除逻辑的接口，所有状态都使用同一接口
				updateTenantStatus(tenant).then(response => {
					if (this.statusForm.isFlag === 0 || this.statusForm.isFlag === 2) {
						this.$modal.msgSuccess("状态修改成功，相关钥匙已被删除");
					} else {
						this.$modal.msgSuccess("状态修改成功");
					}
					this.statusDialog = false;
					this.getList();
				});
			},
			/** 处理详情按钮操作 */
			handleDetail(row) {
				// 如果有homeId，使用新的API查询入住用户信息
				if (this.homeId) {
					getTenantRuzhuInfo({
						id: row.id,
						homeId: this.homeId
					}).then(async response => {
						this.detailForm = response.data;

						// 处理学生照片URL，使用全局工具类
						if (this.detailForm.idCardPositive) {
							this.detailForm.idCardPositive = formatOssUrl(this.detailForm.idCardPositive);
						}

						if (this.detailForm.idCardReverse) {
							this.detailForm.idCardReverse = formatOssUrl(this.detailForm.idCardReverse);
						}

						// 确保位置信息字段存在，即使为空也要定义
						this.detailForm.cellName = this.detailForm.cellName || '';
						this.detailForm.unitName = this.detailForm.unitName || '';
						this.detailForm.floorName = this.detailForm.floorName || '';
						this.detailForm.roomName = this.detailForm.roomName || '';

						this.activeTab = 'base';
						this.detailOpen = true;
					});
				} else {
					// 如果没有homeId，使用原来的API
					getTenant(row.id).then(async response => {
						this.detailForm = response.data;

						// 处理学生照片URL，使用全局工具类
						if (this.detailForm.idCardPositive) {
							this.detailForm.idCardPositive = formatOssUrl(this.detailForm.idCardPositive);
						}

						if (this.detailForm.idCardReverse) {
							this.detailForm.idCardReverse = formatOssUrl(this.detailForm.idCardReverse);
						}

						// 确保位置信息字段存在，即使为空也要定义
						this.detailForm.cellName = this.detailForm.cellName || '';
						this.detailForm.unitName = this.detailForm.unitName || '';
						this.detailForm.floorName = this.detailForm.floorName || '';
						this.detailForm.roomName = this.detailForm.roomName || '';

						this.activeTab = 'base';
						this.detailOpen = true;
					});
				}
			},

			/** 授权钥匙按钮操作 */
			handleKeyAuth(row) {
				this.$refs.keyAuth.showDialog({
					id: row.id,
					homeId: this.queryParams.homeId,
					cellId: row.cellId,
					unitId: row.unitId,
					floorId: row.floorId,
					phone: row.phone,
					idCardNumber: row.idCardNumber,
					name: row.name,
					type: "1", // 默认为密码类型
					cardNo: row.cardNo // 新增：传递卡号
				});
			},
			/** 监听标签页切换 */
			handleTabChange(tab) {
				if (tab.name === 'keys' && this.currentTenantForKey) {
					this.loadKeyList();
				}
			},
			/** 加载钥匙列表 */
			loadKeyList() {
				if (!this.currentTenantForKey) return;

				this.keyLoading = true;
				listTenantkey({
					idCardNumber: this.currentTenantForKey.idCardNumber,
					homeId: this.currentTenantForKey.homeId
				}).then(response => {
					this.keyList = response.rows || [];
					this.keyLoading = false;
				}).catch(() => {
					this.keyLoading = false;
				});
			},
			/** 新增钥匙 */
			handleAddKey() {
				if (!this.currentTenantForKey) return;

				this.$refs.keyAuth.showDialog({
					id: this.currentTenantForKey.id,
					homeId: this.currentTenantForKey.homeId,
					cellId: this.currentTenantForKey.cellId,
					unitId: this.currentTenantForKey.unitId,
					floorId: this.currentTenantForKey.floorId,
					idCardNumber: this.currentTenantForKey.idCardNumber,
					phone: this.currentTenantForKey.phone,
					name: this.currentTenantForKey.name,
					type: "1", // 默认为密码类型
					cardNo: this.currentTenantForKey.cardNo // 新增：传递卡号
				});

				// 添加事件监听，当钥匙授权完成后刷新钥匙列表
				this.$refs.keyAuth.$once('refresh', () => {
					this.loadKeyList();
				});
			},
			/** 编辑钥匙 */
			handleEditKey(row) {
				if (!this.currentTenantForKey) return;

				this.$refs.keyAuth.showDialog({
					keyId: row.id, // 传递钥匙ID，表示是编辑操作
					id: this.currentTenantForKey.id,
					homeId: row.homeId,
					cellId: row.cellId,
					unitId: row.unitId,
					floorId: row.floorId,
					idCardNumber: row.idCardNumber,
					name: this.currentTenantForKey.name,
					type: row.type,
					password: row.password,
					startTime: row.startTime,
					endTime: row.endTime
				});

				// 添加事件监听，当钥匙编辑完成后刷新钥匙列表
				this.$refs.keyAuth.$once('refresh', () => {
					this.loadKeyList();
				});
			},
			/** 删除钥匙 */
			handleDeleteKey(row) {
				this.$modal.confirm('是否确认删除该钥匙？').then(() => {
					delTenantkey(row.id).then(() => {
						this.$modal.msgSuccess("删除成功");
						this.loadKeyList();
					});
				}).catch(() => {});
			},
			/** 修改密码按钮操作 */
			handlePasswordUpdate(row) {
				this.passwordForm = {
					id: row.id,
					password: row.password || ''
				};
				this.passwordOpen = true;
			},
			/** 提交密码修改 */
			submitPasswordForm() {
				this.$refs["passwordForm"].validate(valid => {
					if (valid) {
						const updateData = {
							id: this.passwordForm.id,
							password: this.passwordForm.password,
							operationType: "password"
						};
						updateTenantkey(updateData).then(response => {
							this.$modal.msgSuccess("密码修改成功");
							this.passwordOpen = false;
							this.loadKeyList();
						});
					}
				});
			},
			/** 取消密码修改 */
			cancelPassword() {
				this.passwordOpen = false;
				this.passwordForm = {};
			},
			/** 新增未入住用户对话框 */
			handleAddUserDialog() {
				// 这里是弹出未入住用户选择对话框的逻辑
				this.notRuzhuUserQuery.homeId = this.queryParams.homeId;
				this.notRuzhuUserQuery.pageNum = 1;
				this.searchKeyword = ''; // 重置搜索关键词
				this.notRuzhuUserQuery.name = ''; // 重置姓名搜索字段
				this.notRuzhuUserQuery.idCardNumber = ''; // 重置学工号搜索字段
				this.getNotRuZhuUserList();
				this.addUserDialogVisible = true;
				// 重置选择和时间
				this.selectedUserIds = [];
				this.allSelectedUsers = []; // 重置已选择用户
				this.batchForm = {
					startTime: null,
					endTime: null
				};
			},
			/** 处理未入住用户选择确认 */
			handleAddUserConfirm() {
				if (this.allSelectedUsers.length === 0) {
					this.$message.warning('请选择要添加的用户');
					return;
				}

				// 验证表单
				this.$refs.batchForm.validate(valid => {
					if (valid) {
						const addUsers = this.allSelectedUsers.map(user => ({
							homeId: this.queryParams.homeId,
							userId: user.key,
							startTime: this.batchForm.startTime,
							endTime: this.batchForm.endTime
						}));
						addHomeUser(addUsers).then(() => {
							this.$modal.msgSuccess("添加成功");
							this.addUserDialogVisible = false;
							this.selectedUserIds = [];
							this.allSelectedUsers = [];
							this.batchForm = {
								startTime: null,
								endTime: null
							};
							this.getList();
						}).catch(error => {
							console.error('添加入住用户失败:', error);
							this.$modal.msgError("添加失败");
						});
					} else {
						this.$message.warning('请完善入住时间信息');
						return false;
					}
				});
			},
			/** 获取未入住用户列表 */
			getNotRuZhuUserList() {
				this.notRuzhuUserLoading = true;

				listTenantNotRuzhu(this.notRuzhuUserQuery).then(res => {
					// 构建新的用户列表
					const newUserList = (res.rows || []).map(user => ({
						key: user.id,
						label: user.name + '（' + user.idCardNumber + '）',
						name: user.name,
						idCardNumber: user.idCardNumber
					}));

					// 更新用户列表
					this.notRuzhuUserList = newUserList;
					this.notRuzhuUserTotal = res.total || 0;

					// 不修改已选择的用户ID，保持右侧选择状态

					this.notRuzhuUserLoading = false;
				}).catch(() => {
					this.notRuzhuUserLoading = false;
				});
			},

			/** 未入住用户分页大小改变 */
			handleNotRuzhuUserSizeChange(size) {
				this.notRuzhuUserQuery.pageSize = size;
				this.notRuzhuUserQuery.pageNum = 1;
				this.getNotRuZhuUserList();
			},

			/** 未入住用户当前页改变 */
			handleNotRuzhuUserCurrentChange(page) {
				this.notRuzhuUserQuery.pageNum = page;
				this.getNotRuZhuUserList();
			},



			/** 搜索输入事件处理 */
			handleSearchInput() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}

				// 设置防抖定时器，300ms后执行搜索
				this.searchTimer = setTimeout(() => {
					// 重置分页到第一页
					this.notRuzhuUserQuery.pageNum = 1;

					// 如果搜索关键词为空，清空搜索字段
					if (!this.searchKeyword || this.searchKeyword.trim() === '') {
						this.notRuzhuUserQuery.name = '';
						this.notRuzhuUserQuery.idCardNumber = '';
					} else {
						// 将搜索关键词同时设置到姓名和学工号字段
						this.notRuzhuUserQuery.name = this.searchKeyword;
						this.notRuzhuUserQuery.idCardNumber = this.searchKeyword;
					}

					// 调用后端接口搜索
					this.getNotRuZhuUserList();
				}, 300);
			},

			/** 搜索清除事件处理 */
			handleSearchClear() {
				// 清除搜索关键词
				this.searchKeyword = '';
				// 重置分页到第一页
				this.notRuzhuUserQuery.pageNum = 1;
				// 清除姓名和学工号搜索字段
				this.notRuzhuUserQuery.name = '';
				this.notRuzhuUserQuery.idCardNumber = '';
				// 重新加载数据
				this.getNotRuZhuUserList();
			},

			/** 获取穿梭框数据源 */
			getTransferData() {
				// 合并左侧搜索结果和右侧已选择用户
				const leftData = this.notRuzhuUserList.filter(user =>
					!this.selectedUserIds.includes(user.key)
				);
				const rightData = this.allSelectedUsers;

				return [...leftData, ...rightData];
			},

			/** 穿梭框变化事件处理 */
			handleTransferChange(value, direction, movedKeys) {
				if (direction === 'right') {
					// 用户被移动到右侧（选择）
					movedKeys.forEach(key => {
						const user = this.notRuzhuUserList.find(u => u.key === key);
						if (user && !this.allSelectedUsers.find(u => u.key === key)) {
							this.allSelectedUsers.push(user);
						}
					});
				} else if (direction === 'left') {
					// 用户被移动到左侧（取消选择）
					movedKeys.forEach(key => {
						this.allSelectedUsers = this.allSelectedUsers.filter(u => u.key !== key);
					});
				}
			},

			/** 退房按钮操作 */
			handleCheckOut(row) {
				this.$confirm(
					`确认要为 ${row.name} 办理退房吗？\n\n⚠️ 注意：退房操作将删除该房间下的所有卡片和密码授权。`,
					'退房确认',
					{
						confirmButtonText: '确定退房',
						cancelButtonText: '取消',
						type: 'warning',
						dangerouslyUseHTMLString: true,
						message: `
							<div style="text-align: left;">
								<p><strong>确认要为 ${row.name} 办理退房吗？</strong></p>
								<div style="margin-top: 10px; padding: 10px; background-color: #fef0f0; border-left: 3px solid #f56c6c; border-radius: 4px;">
									<p style="margin: 0; color: #f56c6c; font-weight: bold;">⚠️ 重要提示：</p>
									<p style="margin: 5px 0 0 0; color: #f56c6c;">退房操作将删除该房间下的所有卡片和密码授权，此操作不可恢复！</p>
								</div>
							</div>
						`
					}
				).then(() => {
					this.processCheckOut(row);
				}).catch(() => {
					// 用户取消操作
				});
			},

			/** 执行退房操作 */
			processCheckOut(row) {
				const checkOutData = {
					homeId: this.queryParams.homeId, // 房间ID
					userId: row.id // 用户ID
				};

				apartmentRoomSingleCheckOut(checkOutData).then(response => {
					if (response.resultCode === 0) {
						this.$modal.msgSuccess("退房成功，该房间下的所有卡片和密码授权已被删除");
						// 刷新列表
						this.getList();
					} else {
						// 根据不同的错误码显示不同的错误信息
						let errorMessage = "退房失败";
						switch (response.resultCode) {
							case 500001:
								errorMessage = "参数异常：" + (response.reason || "房间ID和用户ID不能为空");
								break;
							case 500002:
								errorMessage = "房间不存在";
								break;
							case 500003:
								errorMessage = "房间未关联门锁";
								break;
							case 500004:
								errorMessage = "房间不存在该房客";
								break;
							case 500005:
								errorMessage = "Token异常：" + (response.reason || "认证失败");
								break;
							case 500006:
								errorMessage = "请求异常：" + (response.reason || "网络错误");
								break;
							case 500007:
								errorMessage = response.reason || "该用户已经退房了";
								break;
							default:
								errorMessage = "退房失败：" + (response.reason || "未知错误");
								break;
						}
						this.$modal.msgError(errorMessage);
					}
				}).catch(error => {
					console.error('退房请求失败:', error);
					this.$modal.msgError("退房请求失败，请稍后重试");
				});
			},

			/** 房间退租按钮操作 */
			handleRoomCheckOut() {
				if (!this.queryParams.homeId) {
					this.$modal.msgError("请先选择房间");
					return;
				}

				this.$confirm(
					`确认要对该房间进行退租操作吗？\n\n⚠️ 注意：房间退租将删除该房间下的所有用户、卡片和密码授权。`,
					'房间退租确认',
					{
						confirmButtonText: '确定退租',
						cancelButtonText: '取消',
						type: 'warning',
						dangerouslyUseHTMLString: true,
						message: `
							<div style="text-align: left;">
								<p><strong>确认要对该房间进行退租操作吗？</strong></p>
								<div style="margin-top: 10px; padding: 10px; background-color: #fef0f0; border-left: 3px solid #f56c6c; border-radius: 4px;">
									<p style="margin: 0; color: #f56c6c; font-weight: bold;">⚠️ 重要提示：</p>
									<p style="margin: 5px 0 0 0; color: #f56c6c;">房间退租将删除该房间下的所有用户、卡片和密码授权，此操作不可恢复！</p>
								</div>
							</div>
						`
					}
				).then(() => {
					this.processRoomCheckOut();
				}).catch(() => {
					// 用户取消操作
				});
			},

			/** 执行房间退租操作 */
			processRoomCheckOut() {
				const roomCheckOutData = {
					roomId: this.queryParams.homeId // 房间ID
				};

				roomCheckOut(roomCheckOutData).then(response => {
					if (response.resultCode === 0) {
						this.showRoomCheckOutResult(response.data, 'success');
						// 刷新列表
						this.getList();
					} else {
						// 根据不同的错误码显示不同的错误信息
						let errorMessage = "房间退租失败";
						switch (response.resultCode) {
							case 500001:
								errorMessage = "房间不能为空：" + (response.reason || "房间ID参数错误");
								break;
							case 500005:
								errorMessage = "Token异常：" + (response.reason || "认证失败，请重新登录");
								break;
							case 500006:
								errorMessage = "请求异常：" + (response.reason || "网络或服务器错误");
								break;
							default:
								errorMessage = "房间退租失败：" + (response.reason || "未知错误，错误码：" + response.resultCode);
								break;
						}
						this.$modal.msgError(errorMessage);
					}
				}).catch(error => {
					console.error('房间退租请求失败:', error);
					this.$modal.msgError("房间退租请求失败，请稍后重试");
				});
			},

			/** 显示房间退租结果 */
			showRoomCheckOutResult(data, type) {
				const totalUsers = data.totalUsers || 0;
				const successCount = data.successCount || 0;
				const cleanedCount = data.cleanedCount || 0;
				const roomName = data.roomName || '未知房间';

				let title = '房间退租成功';
				let type_ = 'success';
				let message = `房间"${roomName}"退租成功！\n\n总计：${totalUsers} 个用户`;

				if (cleanedCount > 0) {
					// 清理脏数据的情况
					message += `\n清理脏数据：${cleanedCount} 个用户`;

					// 如果有清理的用户，显示详细信息
					if (data.cleanedUsers && data.cleanedUsers.length > 0) {
						message += '\n\n清理脏数据用户：';
						data.cleanedUsers.forEach((user, index) => {
							message += `\n${index + 1}. ${user.userName || '未知用户'} - ${user.cleanReason || '脏数据已清理'}`;
						});
					}
				} else {
					// 正常退房成功的情况
					message += `\n成功退房：${successCount} 个用户`;

					// 如果有成功退房的用户，显示详细信息
					if (data.successUsers && data.successUsers.length > 0) {
						message += '\n\n退房用户详情：';
						data.successUsers.forEach((user, index) => {
							message += `\n${index + 1}. ${user.userName || '未知用户'}`;
						});
					}
				}

				this.$alert(message, title, {
					confirmButtonText: '确定',
					type: type_,
					center: true,
					customClass: 'room-checkout-result-dialog'
				});
			},
			
			/** 计算表格最大高度 */
			calculateTableHeight() {
				this.$nextTick(() => {
					const container = this.$el.querySelector('.app-container');
					if (container) {
						const containerHeight = container.clientHeight;
						const windowHeight = window.innerHeight;
						
						// 如果是嵌入模式，使用更小的最大高度
						if (this.isEmbedded) {
							this.tableMaxHeight = Math.min(400, containerHeight - 80);
						} else {
							// 正常模式，计算可用高度
							// 减去工具栏、分页等固定元素的高度
							const toolbarHeight = 60; // 工具栏高度
							const paginationHeight = 50; // 分页高度
							const marginHeight = 40; // 其他边距
							
							const availableHeight = windowHeight - toolbarHeight - paginationHeight - marginHeight;
							this.tableMaxHeight = Math.max(300, Math.min(600, availableHeight));
						}
					}
				});
			},

			/** 当入住时间改变时，重新验证离开时间 */
			onStartTimeChange() {
				if (this.form.endTime) {
					this.$refs.form.validateField('endTime');
				}
			},

			/** 当批量入住时间改变时，重新验证离开时间 */
			onBatchStartTimeChange() {
				if (this.batchForm.endTime) {
					this.$refs.batchForm.validateField('endTime');
				}
			},
		},

		// 组件销毁时清理定时器
		beforeDestroy() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}
			// 移除窗口大小变化监听器
			window.removeEventListener('resize', this.calculateTableHeight);
		}
	};
</script>

<style lang="scss">
	.el-dialog__title {
		color: #303133;
		font-weight: 500;
		font-size: 16px;
	}

	.mt20 {
		margin-top: 20px;
	}

	.id-card-box {
		border: 1px solid #ebeef5;
		border-radius: 4px;
		padding: 15px;
		text-align: center;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
		transition: all 0.3s;
		height: 320px;
		display: flex;
		flex-direction: column;

		&:hover {
			box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.1);
		}

		h4 {
			margin-top: 0;
			margin-bottom: 15px;
			color: #303133;
			font-weight: 500;
		}

		.el-image {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;

			img {
				max-width: 100%;
				max-height: 100%;
				object-fit: contain;
			}
		}
	}

	.image-error {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 150px;
		color: #f56c6c;
		font-size: 14px;
		background-color: #fef0f0;
		border-radius: 4px;

		i {
			font-size: 30px;
			margin-bottom: 10px;
		}
	}

	.image-loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 150px;
		color: #409eff;
		font-size: 14px;
		background-color: #f5f7fa;
		border-radius: 4px;

		i {
			font-size: 30px;
			margin-bottom: 10px;
		}
	}

	.location-info {
		display: flex;
		flex-wrap: wrap;
		gap: 5px;

		.location-item {
			position: relative;
			padding-right: 15px;

			&:not(:last-child)::after {
				content: '>';
				position: absolute;
				right: 0;
				color: #909399;
			}
		}
	}

	.contract-attachments-simple {
		padding: 10px;
		background-color: #fff;
		border-radius: 4px;
		border: 1px solid #ebeef5;

		.attachment-title {
			font-weight: 500;
			margin-bottom: 10px;
		}

		.attachment-list {
			list-style: none;
			padding: 0;
			margin: 0;

			li {
				margin-bottom: 5px;

				.download-link {
					color: #409eff;
					text-decoration: none;

					&:hover {
						text-decoration: underline;
					}
				}
			}
		}
	}

	.text-danger {
		color: #f56c6c;
		font-weight: bold;
	}

	.text-warning {
		color: #e6a23c;
		font-weight: bold;
	}

	.text-success {
		color: #67c23a;
	}

	.remaining-days-item {
		.el-descriptions-item__content {
			display: flex;
			align-items: center;

			span {
				display: inline-block;
				padding: 2px 8px;
				border-radius: 4px;

				&.text-danger {
					background-color: #fef0f0;
				}

				&.text-warning {
					background-color: #fdf6ec;
				}

				&.text-success {
					background-color: #f0f9eb;
				}
			}
		}
	}

	/* 嵌入模式样式优化 */
	.app-container {
		&.embedded-mode {
			padding: 0;
			margin: 0;

			.el-table {
				margin-bottom: 0;
			}

			.el-pagination {
				margin-top: 10px;
				justify-content: center;
			}
		}
	}

	/* 表格滚动样式优化 */
	.el-table {
		.el-table__body-wrapper {
			overflow-y: auto;
			
			/* 自定义滚动条样式 */
			&::-webkit-scrollbar {
				width: 8px;
			}
			
			&::-webkit-scrollbar-track {
				background: #f1f1f1;
				border-radius: 4px;
			}
			
			&::-webkit-scrollbar-thumb {
				background: #c1c1c1;
				border-radius: 4px;
				
				&:hover {
					background: #a8a8a8;
				}
			}
		}
		
		/* 确保表格头部固定 */
		.el-table__header-wrapper {
			position: sticky;
			top: 0;
			z-index: 2;
			background: #fff;
		}
		
		/* 响应式表格样式 */
		@media (max-width: 768px) {
			font-size: 12px;
			
			.el-table__header-wrapper {
				.el-table__header {
					th {
						padding: 8px 4px;
						font-size: 12px;
					}
				}
			}
			
			.el-table__body-wrapper {
				.el-table__body {
					td {
						padding: 6px 4px;
						font-size: 12px;
					}
				}
			}
		}
	}

	.key-management {
		.key-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;

			h3 {
				margin: 0;
				font-size: 16px;
				font-weight: 500;
			}
		}
	}

	.warning-tip {
		margin-top: 10px;
		padding: 8px 10px;
		background-color: #fef0f0;
		border-radius: 4px;
		color: #f56c6c;
		font-size: 13px;
		display: flex;
		align-items: center;
		line-height: 1.4;

		i {
			margin-right: 8px;
			font-size: 16px;
		}
	}

	/* 批量添加用户对话框样式 */
	.batch-add-dialog {
		>>> .el-dialog {
				max-height: 95vh;
			display: flex;
			flex-direction: column;
		}

		>>> .el-dialog__body {
			flex: 1;
			overflow: hidden;
			padding: 20px;
		}

		>>> .el-dialog__footer {
			flex-shrink: 0;
		}

		.dialog-content {
			padding: 0;
			height: 100%;
		}

		.user-selection-section {
			height: 100%;
			padding: 24px;
			background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
			border-radius: 12px;
			border: 1px solid #e9ecef;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
			display: flex;
			flex-direction: column;
			min-height: 550px;
		}

		.time-setting-section {
			height: 100%;
			padding: 24px;
			background: linear-gradient(135deg, #f0f7ff 0%, #ffffff 100%);
			border-radius: 12px;
			border: 1px solid #d1ecf1;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
			transition: all 0.3s ease;
			display: flex;
			flex-direction: column;
			min-height: 500px;

			&.time-section-active {
				background: linear-gradient(135deg, #e6f3ff 0%, #ffffff 100%);
				border-color: #409eff;
				box-shadow: 0 6px 16px rgba(64, 158, 255, 0.15);
			}
		}

		.section-header {
			display: flex;
			align-items: center;
			margin-bottom: 12px;

			i {
				font-size: 18px;
				margin-right: 8px;
				color: #409eff;
			}

			.section-title {
				font-size: 16px;
				font-weight: 600;
				color: #303133;
				margin-right: 12px;
			}

			.required-badge {
				background: linear-gradient(45deg, #ff6b6b, #ee5a52);
				color: white;
				padding: 2px 8px;
				border-radius: 12px;
				font-size: 11px;
				font-weight: 500;
				text-transform: uppercase;
				letter-spacing: 0.5px;
			}
		}

		.selection-tip {
			display: flex;
			flex-direction: column;
			margin-bottom: 16px;
			padding: 8px 12px;
			background-color: #f0f9ff;
			border-radius: 6px;
			border-left: 3px solid #409eff;

			> div:first-child {
				display: flex;
				align-items: center;
			}

			i {
				color: #409eff;
				margin-right: 8px;
				font-size: 14px;
			}

			span {
				color: #606266;
				font-size: 13px;
				line-height: 1.4;
			}

			.user-count-tip {
				margin-top: 8px;
				padding-top: 8px;
				border-top: 1px solid #e1f3ff;

				span {
					color: #409eff;
					font-size: 12px;
					font-weight: 500;
				}
			}
		}

		.transfer-container {
			flex: 1;
			display: flex;
			flex-direction: column;
			min-height: 400px;
			position: relative;
		}

		.search-container {
			padding: 0 8px;
		}

		.transfer-pagination {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			text-align: center;
			padding: 10px 0;
			border-top: 1px solid #e4e7ed;
			background-color: #f8f9fa;
			border-radius: 0 0 6px 6px;
			z-index: 10;
		}

		.custom-transfer {
			width: 100%;
			flex: 1;
			display: flex;
			flex-direction: row;
			align-items: stretch;
			margin-bottom: 60px; /* 为分页组件留出空间 */



			.el-transfer-panel {
				flex: 1;
				border-radius: 6px;
				border: 1px solid #dcdfe6;
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
				display: flex;
				flex-direction: column;
				min-height: 200px;
				max-height: 340px; /* 限制最大高度，避免与分页冲突 */
				margin: 0 8px;

				.el-transfer-panel__header {
					height: 40px;
    line-height: 40px;
    background: #F5F7FA;
    margin: 0;
    padding-left: 15px;
    border-bottom: 1px solid #e6ebf5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #000000;

					.el-transfer-panel__title {
						font-weight: 600;
						color: #303133;
						font-size: 14px;
						text-align: center;
						line-height: 1.4;
					}
				}

				.el-transfer-panel__body {
					flex: 1;
					overflow: hidden;
					max-height: 240px; /* 为头部和底部留出空间 */

					.el-transfer-panel__list {
						height: 100%;
						overflow-y: auto;
						padding: 8px;

						.el-transfer-panel__item {
							border-radius: 4px;
							transition: all 0.2s ease;
							border: 1px solid transparent;

							&:hover {
								background-color: #f5f7fa;
								transform: translateX(2px);
								border-color: #e4e7ed;
							}

							&.is-checked {
								background-color: #ecf5ff;
								color: #409eff;
								border-color: #409eff;
							}
						}
					}
				}
			}

			.el-transfer__buttons {
				padding: 0 15px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.el-button {
					border-radius: 50%;
					width: 36px;
					height: 36px;
					padding: 0;
					margin: 8px 0;
					box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
					transition: all 0.2s ease;

					&:hover {
						transform: scale(1.05);
						box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
					}
				}
			}
		}

		.time-content {
			flex: 1;
			animation: fadeInUp 0.3s ease;
			display: flex;
			flex-direction: column;
		}

		.time-placeholder {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			flex: 1;
			color: #909399;

			.placeholder-icon {
				font-size: 48px;
				margin-bottom: 16px;
				color: #c0c4cc;
				animation: pulse 2s infinite;
			}

			.placeholder-text {
				text-align: center;

				p {
					font-size: 16px;
					font-weight: 500;
					margin: 0 0 8px 0;
					color: #606266;
				}

				span {
					font-size: 13px;
					color: #909399;
					line-height: 1.4;
				}
			}
		}

		.time-form {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.el-form-item {
				margin-bottom: 24px;

				.el-form-item__label {
					font-weight: 500;
					color: #606266;
				}

				.el-date-editor {
					border-radius: 6px;
					border: 1px solid #dcdfe6;
					transition: all 0.2s ease;

					&:hover {
						border-color: #c0c4cc;
					}

					&.is-focus {
						border-color: #409eff;
						box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
					}
				}
			}
		}

		.dialog-footer {
			text-align: right;
			padding-top: 20px;
			border-top: 1px solid #e4e7ed;

			.el-button {
				border-radius: 6px;
				font-weight: 500;
				transition: all 0.2s ease;

				&:hover {
					transform: translateY(-1px);
					box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
				}
			}
		}
	}

	/* 动画关键帧 */
	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(20px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes pulse {
		0%, 100% {
			opacity: 0.6;
			transform: scale(1);
		}
		50% {
			opacity: 1;
			transform: scale(1.05);
		}
	}

	/* 房间退租结果对话框样式 */
	.room-checkout-result-dialog {
		.el-message-box__content {
			max-height: 400px;
			overflow-y: auto;
			white-space: pre-line;
			line-height: 1.6;
			font-size: 14px;
		}

		.el-message-box__message {
			text-align: left;
			padding: 10px 0;
		}
	}

	/* 隐藏日期选择器的此刻按钮 */
	.currentDatePickerClass .el-picker-panel__footer .el-picker-panel__link-btn:first-child {
		display: none !important;
	}
	
	/* 备用方案：使用更具体的选择器 */
	.currentDatePickerClass .el-picker-panel__footer .el-button.el-picker-panel__link-btn.el-button--text:first-child {
		display: none !important;
	}
	
	/* 全局隐藏所有日期选择器的此刻按钮 */
	.el-picker-panel__footer .el-picker-panel__link-btn:first-child {
		display: none !important;
	}
	
	/* 更具体的全局选择器 */
	.el-picker-panel__footer .el-button.el-picker-panel__link-btn.el-button--text:first-child {
		display: none !important;
	}
</style>
